package top.bluesword.laboratory.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 李林峰
 */
@RestController
@RequestMapping("sse")
@Slf4j
public class SseController {

    private final Map<String,SseEmitter> sseEmitterMap = new HashMap<>();

    @PostMapping
    public SseEmitter sse(String sessionId, HttpServletRequest request) throws IOException {
        log.debug("sseEmitterMap keys:{}",sseEmitterMap.keySet());
        if (StringUtils.isBlank(sessionId)) {
            sessionId = UUID.randomUUID().toString();
        }
        SseEmitter sseEmitter = sseEmitterMap.computeIfAbsent(
            sessionId, k -> {
                SseEmitter emitter = new SseEmitter(60 * 60 * 1000L);
                emitter.onCompletion(() -> {
                    log.debug("{} 完成",k);
                    sseEmitterMap.remove(k);
                });
                emitter.onError(throwable -> log.error("出现异常",throwable));
                emitter.onTimeout(() -> log.info("连接超时"));
                return emitter;
            }
        );
        String remoteAddr = request.getRemoteAddr();
        sseEmitter.send(
            SseEmitter
                .event()
                .name("加入连接")
                .data(remoteAddr)
        );
        sseEmitter.send(
            MessageFormat.format("普通消息 id:{0} 内容：{1}", sessionId, remoteAddr)
        );
        return sseEmitter;
    }

    @PutMapping(value="{sessionId}")
    public String message(@PathVariable("sessionId") String sessionId,String message) throws IOException {
        SseEmitter sseEmitter = sseEmitterMap.get(sessionId);
        if (sseEmitter == null) {
            return "会话不存在";
        }
        sseEmitter.send(message);
        return "发送成功";
    }

    @DeleteMapping(value="{sessionId}")
    public void complete(@PathVariable("sessionId") String sessionId) {
        SseEmitter sseEmitter = sseEmitterMap.get(sessionId);
        if (sseEmitter != null) {
            sseEmitter.complete();
        }
    }

}